<?php

namespace app\api\model\user;

use app\common\model\user\PointsLog as PointsLogModel;
use app\api\model\User as UserModel;
use app\api\model\Setting as SettingModel;

/**
 * 用户余额变动明细模型
 * Class PointsLog
 * @package app\api\model\user
 */
class PointsLog extends PointsLogModel
{
    /**
     * 获取日志明细列表
     * @param $userId
     * @param $type
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($userId, $type = 'all')
    {
        // 筛选条件
        $filter = [];
        // 订单数据类型
        switch ($type) {
            case 'all':
                break;
            case 'payment';
                $filter['scene'] = 10;
                break;
            case 'delivery';
                $filter['scene'] = 20;
                break;
        }
        // 获取列表数据
        return $this->with(['goods.image.file', 'pointsgoods.image.file', 'dealeruser'])
            ->where('user_id', '=', $userId)
            ->where($filter)
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 用户分享平台累计积分
     * @param $user_id
     * @return false|int|true
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function userShare($user_id)
    {
        //验证今日是否已分享
        $today = date('Y-m-d');
        if ($this->userShareNumsToday($user_id, $today)) {
            $this->error = '今日已分享';
            return false;
        }
        $values = SettingModel::getItem("store");
        if ($values['user']['share_points'] > 0 && !empty($values['user']['share_points'])) {
            $describe = "用户分享平台";
            $model = UserModel::detail($user_id);
            return $model->setIncPoints($values['user']['share_points'], $describe, $user_id, 20, 10, 20);
        }
        return false;
    }

    /**
     * 返回今日是否已经分享
     * @param $user_id
     * @param null $day
     * @return int|string
     */
    public function userShareNumsToday($user_id, $day = null)
    {
        $filter = [];
        if (!is_null($day)) {
            $startTime = strtotime($day);
            $filter['create_time'] = [
                ['>=', $startTime],
                ['<', $startTime + 86400],
            ];
        }
        return $this->where($filter)->where(['user_id' => $user_id, 'scene_type' => 20])->count();
    }

    /**
     * 返回今日是否已经分享
     * @param $user_id
     * @return bool
     */
    public static function userIsShareToday($user_id)
    {
        $startTime = strtotime(date('Y-m-d'));
        $filter['create_time'] = [
            ['>=', $startTime],
            ['<', $startTime + 86400],
        ];
        if (self::where($filter)->where(['user_id' => $user_id, 'scene_type' => 20])->count() > 0) {
            return false;
        }
        return true;
    }

}